package com.igeek.health.config;


import cn.hutool.json.JSONUtil;
import com.igeek.health.result.Result;
import com.igeek.health.utils.WebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author chenmin
 * @Description TODO
 * @Date 2023/12/22
 *
 * 1.如果项目中 没有针对 全局异常提供处理 则可以配置 SecurityHandler
 * 2.如果项目中 存在  全局异常提供处理 则可以不配置SecurityHandler 转到HealthControllerAdvice中来处理异常
 */
@Component
public class SecurityHandler {

    //授权失败 403
    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        return new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                //Result result = new Result(403, "403您的权限不足!");
                Result result = new Result(false, "403您的权限不足!");
                String json = JSONUtil.toJsonStr(result);
                // 将字符串渲染到客户端
                WebUtils.renderString(response, json);
            }
        };
    }


    //认证失败 401
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint(){
        return new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                //Result result = new Result(401, "401认证失败，请重新登录!");
                Result result = new Result(false, "401认证失败，请重新登录!");
                String json = JSONUtil.toJsonStr(result);
                // 将字符串渲染到客户端
                WebUtils.renderString(response, json);
            }
        };
    }

}
